<?php

/**
 * Created by PhpStorm.
 * User: hongyeah
 * Date: 2015/10/21
 * Time: 21:23
 */
namespace Admin\Model;
use Common\Common\MyPage;
use Think\Model;

class UsersModel extends Model
{
    /**
     * return 0代表重复 1代表添加失败 2代表成功
     * */
    public function addUsers($data){
        $exist =$this->where(array('cardnum'=>$data['cardnum']))->find();

        if(!empty($exist)){
            return 0;
        }

        $result =  $this->data($data)->add();

        if(!$result){
            return 1;
        }else{
            return 2;
        }
    }

    public function delUsersByCardNum($cardnum){
        $where['cardnum'] = $cardnum;
        $result = $this->where($where)->count();
        if($result!=0){
            $id = $this->field('person_id')->where($where)->find();
            M('record')->where("person_id=%d",$id)->delete();
            $this->where($where)->delete();
            return true;
        }else{
            return false;
        }
    }

    public function delUsersById($ids){

        $where['person_id'] = array('in',$ids);
        $result = $this->where($where)->delete();
        if(!$result) return false;
        M('record')->where($where)->delete();
        return true;

    }

    public function edtUsers($data){
        $exist = $this->where(array('cardnum' => $data['cardnum']))->find();
        if(empty($exist)){
            return false;
        }

        $this->where(array('cardnum' => $data['cardnum']))->save($data);

        return true;
    }

    public function getUsersByNum($cardnum){
        $data = $this->where(array('cardnum'=>$cardnum))->find();
        return $data;
    }
    public function getUsersByID($id){
        $data = $this->where(array('person_id'=>$id))->find();
        return $data;
    }

    public function getUsersList($search='',$page_size=15){
        $data = new \stdClass();


        if($search==''){
            $where = array(
                'cardnum' => array('LIKE','%'.$search.'%'),
            );
        }else{
            $where['person_id'] = array('gt',1);
            $where['_string'] = ' (cardnum like '.'\'%'.$search.'%\''.')  OR ( name like '.'\'%'.$search.'%\''.') ';
        }

        $count = $this->where($where)->count();

        $Page = new MyPage($count,$page_size);

        $data->show = $Page->showData();

        $dds = $this->where($where)->field('person_id,cardnum,name')->limit($Page->firstRow.','.$Page->listRows)->select();

        $data->data = $dds;

        return $data;
    }


}
